//
//  MLImageView.m
//  Pods
//
//  Created by molon on 15/7/1.
//
//

#import "MLImageView.h"
#import <UIImageView+WebCache.h>
#import "UIImage+MLKit.h"
#import "MLKitDefine.h"
#import "UIView+MLKit.h"

#define kActivityIndicatorTag 8888
#define kRetryButtonTag 100

@interface MLImageView()

@property (nonatomic,strong) NSURL *lastUrl;
@property (nonatomic,strong) UIImage *lastPlaceholderImage;
@property (nonatomic, assign) SDWebImageOptions lastOptions;
@property (nonatomic, copy) SDWebImageDownloaderProgressBlock lastProgressBlock;
@property (nonatomic, copy) SDWebImageCompletionBlock lastCompletionBlock;

@end

@implementation MLImageView

- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock {
    
    self.lastUrl = url;
    self.lastPlaceholderImage = placeholder;
    self.lastOptions = options;
    self.lastProgressBlock = progressBlock;
    self.lastCompletionBlock = completedBlock;
    
    if (!url) {
        [super sd_setImageWithURL:url placeholderImage:placeholder options:options progress:progressBlock completed:completedBlock];
        return;
    }
    
    //加载loading
    UIActivityIndicatorView *activityIndicator = (UIActivityIndicatorView*)[self viewWithTag:kActivityIndicatorTag];
    if (!activityIndicator) {
        UIActivityIndicatorViewStyle style = self.indicatorStyle;
        if (style==UIActivityIndicatorViewStyleWhiteLarge) {
            style = placeholder?UIActivityIndicatorViewStyleWhite:UIActivityIndicatorViewStyleGray;
        }
        
        activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:style];
        activityIndicator.tag = kActivityIndicatorTag;
        [self addSubview:activityIndicator];
        
    }
    
    [activityIndicator startAnimating]; //开始loading
    
    UIButton *retryButton = (UIButton *)[self viewWithTag:kRetryButtonTag];
    if (retryButton) {
        [retryButton removeFromSuperview];
    }
    
    __weak __typeof(self)weakSelf = self;
    
    [super sd_setImageWithURL:url placeholderImage:placeholder options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL){
        if (image&&!error) {
            if (cacheType==SDImageCacheTypeNone) {
                [weakSelf simpleTransitionWithDuration:.15f andType:kCATransitionFade];
            }
            
            weakSelf.lastUrl = nil;
            weakSelf.lastPlaceholderImage = nil;
            weakSelf.lastCompletionBlock = nil;
            weakSelf.lastProgressBlock = nil;
        }else{
            [activityIndicator stopAnimating];
            [activityIndicator removeFromSuperview];
            
            if (error.code!=NSURLErrorCancelled) { //不是取消的才用这个
                weakSelf.userInteractionEnabled = YES;
                
                //可点击重新加载
                UIButton *retryButton = (UIButton *)[weakSelf viewWithTag:kRetryButtonTag];
                if (!retryButton) {
                    retryButton = [UIButton buttonWithType:UIButtonTypeCustom];
                    retryButton.backgroundColor = [UIColor clearColor];
                    UIColor *signColor = weakSelf.retryImageColor;
                    if (!signColor) {
                        if (!placeholder) { //没有则使用灰色
                            signColor = [UIColor grayColor];
                        }else{
                            signColor = [UIColor whiteColor];
                        }
                    }
                    UIImage *refreshImage = [[UIImage imageNamed:MLKIT_BUNDLE_FILE(@"刷新")] imageWithTintColor:signColor];
                    [retryButton setImage:refreshImage forState:UIControlStateNormal];
                    [retryButton addTarget:weakSelf action:@selector(retryButtonEvent) forControlEvents:UIControlEventTouchUpInside];
                    retryButton.tag = kRetryButtonTag;
                    
                    [weakSelf addSubview:retryButton];
                }
            }
        }
        
        if (completedBlock) {
            completedBlock(image,error,cacheType,imageURL);
        }
    }];
    
}

- (void)retryButtonEvent
{
    [self sd_setImageWithURL:self.lastUrl placeholderImage:self.lastPlaceholderImage options:(self.lastOptions|SDWebImageRetryFailed) progress:self.lastProgressBlock completed:self.lastCompletionBlock];
}

- (void)layoutSubviews{
    [super layoutSubviews];
    
    UIButton *retryButton = (UIButton*)[self viewWithTag:kRetryButtonTag];
    UIActivityIndicatorView *activityIndicator = (UIActivityIndicatorView*)[self viewWithTag:kActivityIndicatorTag];
    
    if (activityIndicator) {
        activityIndicator.center = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);
    }
    
    if (retryButton) {
        retryButton.frame = self.bounds;
        [self bringSubviewToFront:retryButton];
    }
}


- (void)setImage:(UIImage *)image
{
    [super setImage:image];
    
    if ((!image&&!self.lastPlaceholderImage)||[image isEqual:self.lastPlaceholderImage]) {
        return;
    }
    
    UIActivityIndicatorView *activityIndicator = (UIActivityIndicatorView*)[self viewWithTag:kActivityIndicatorTag];
    if (activityIndicator) {
        [activityIndicator stopAnimating];
        [activityIndicator removeFromSuperview];
    }
    
    UIButton *retryButton = (UIButton*)[self viewWithTag:kRetryButtonTag];
    if (retryButton) {
        [retryButton removeFromSuperview];
    }
}

@end
